<?php


namespace app\api\controller;

use think\Controller;
use think\Db;
use think\Request;
use WeChatPay\Builder;
use WeChatPay\Crypto\Rsa;

class Tixian extends Base
{
    public $merchantId = '1702478872';

    public function bill(Request $request){
        $param = $request->param();
        $user_id = $param['user_id'];
        $openid = Db::table("store_member")->where(['id'=>$user_id])->value('openid');
        $list = Db::table("store_member_bill")->where(['openid'=>$openid])->order("id desc")->select();

        $count = Db::table("store_member_bill")->field("id")->where(['openid'=>$openid,'state'=>'WAIT_USER_CONFIRM'])->count();

        return $this->api_result(200, '请求成功', ['list'=>$list,'count'=>$count]);
    }


    public function shoukuan(Request $request){
        $param = $request->param();
        $id = $param['id'];
        Db::table("store_member_bill")->where(['id'=>$id])->update(['status'=>'已收款','state'=>'SUCCESS']);
        return $this->api_result(200, '请求成功', []);
    }

    public function shoukuan2(Request $request){
        $param = $request->param();
        $id = $param['id'];
        Db::table("store_member_bill")->where(['id'=>$id])->update(['state'=>'FAIL']);
        return $this->api_result(200, '请求成功', []);
    }

        // 从本地文件中加载「商户API私钥」，「商户API私钥」会用来生成请求的签名
    public function name($name,$twoPlatformPublicKeyInstance){
       return Rsa::encrypt($name, $twoPlatformPublicKeyInstance);
    }

    public function index($openid='olLWk7fHOLzxpJFnIU_7A970LeL0',$amount=100,$out_trade_no='',$log_id=0)
    {

        $merchantPrivateKeyFilePath = file_get_contents($this->gen() . 'apiclient_key.pem');

        $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);

        $merchantCertificateSerial = '79056050BF7311F2E85AE07C2EDD1E47DBB36914';


        // 从本地文件中加载「微信支付公钥」，用来验证微信支付应答的签名
        $platformPublicKeyFilePath    = file_get_contents($this->gen() . 'pub_key.pem');
        $twoPlatformPublicKeyInstance = Rsa::from($platformPublicKeyFilePath, Rsa::KEY_TYPE_PUBLIC);

        // 「微信支付公钥」的「微信支付公钥ID」
        // 需要在 商户平台 -> 账户中心 -> API安全 查询
        $platformPublicKeyId = 'PUB_KEY_ID_0117024788722024122500218500000949';

        // 构造一个 APIv3 客户端实例
        $instance = Builder::factory([
            'mchid'      => $this->merchantId,
            'serial'     => $merchantCertificateSerial,
            'privateKey' => $merchantPrivateKeyInstance,
            'certs'      => [
                $platformPublicKeyId => $twoPlatformPublicKeyInstance,
            ],
        ]);

        if(empty($out_trade_no)){
            $out_trade_no = date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        }

        $d['out_trade_no'] = $out_trade_no;
        $d['create_at'] = date('Y-m-d H:i:s');
        $d['openid'] = $openid;
        $d['amount'] = $amount;
        $d['log_id'] = $log_id;
        Db::table("store_member_bill")->insert($d);

        $phone = Db::table("store_member")->where(['openid'=>$d['openid']])->value('phone');
        if($phone){
            $this->sms_tixian($phone);
        }

        $resp = $instance->v3->fundApp->mchTransfer->transferBills->postAsync(
            [ 'json' =>
                [ 'appid' => 'wx10dbf84c62a916f2',
                    'out_bill_no' => $d['out_trade_no'],
                    'openid' => $d['openid'],
                    //'user_name' => $this->name('冯兆东',$twoPlatformPublicKeyInstance),
                    'transfer_amount' => $d['amount'],
                    'transfer_remark' => '会员余额提现',
                    'notify_url' => 'https://app.yinuoxinnengyuan.cn/index.php/api/tixian/callback',
                    'user_recv_perception' => '劳务报酬',
                    'transfer_scene_id' => '1005',
                    'transfer_scene_report_infos' =>
                        [['info_type' => '岗位类型',
                            'info_content' => '外卖员',
                        ],['info_type' => '报酬说明',
                            'info_content' => '7月份配送费',
                        ]],
                ],
                'headers' =>
                    [ 'Wechatpay-Serial' => 'PUB_KEY_ID_0117024788722024122500218500000949',
                    ],
            ])
            ->then(static function(\Psr\Http\Message\ResponseInterface $response) use($d){
                $arr = json_decode((string) $response->getBody(), true);
                $json = json_encode($arr);
                Db::table("store_member_bill")->where(['out_trade_no'=>$d['out_trade_no']])->update(['json'=>$json,'state'=>$arr['state'],'transfer_bill_no'=>$arr['transfer_bill_no'],'package_info'=>$arr['package_info'],'status'=>'未收款']);
            })
            ->wait();
    }


    public function sms_tixian($mobile=18512345769){
        $ishave = Db::table("store_mobile_code2")->where(['mobile'=>$mobile,'type'=>'tixian'])->find();
        if(empty($ishave)){
            $url = "https://api.guoyangyun.com/api/sms/smsoto.htm?appkey=1121362612202412070944571519586&appsecret=e238c0a5f684da68af56af66c2cfe66f&mobile=$mobile&smsSignId=3ff0685b3d464bd09404862b630e2dd2&templateId=e929b039601b4ae8bb3264816244934a";
            $res = file_get_contents($url);
            $arr = json_decode($res,true);
            if($arr){
                if($arr['msg']=='成功'){
                    Db::table("store_mobile_code2")->insert(['mobile'=>$mobile,'type'=>'tixian','add_time'=>date('Y-m-d H:i:s')]);
                }
            }
        }
    }

    public function query_bill(Request $request){
        $param = $request->param();

        $out_bill_no = $param['out_trade_no']??'2025041016304661806';

        $merchantPrivateKeyFilePath = file_get_contents($this->gen() . 'apiclient_key.pem');

        $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);

        $merchantCertificateSerial = '79056050BF7311F2E85AE07C2EDD1E47DBB36914';


        // 从本地文件中加载「微信支付公钥」，用来验证微信支付应答的签名
        $platformPublicKeyFilePath    = file_get_contents($this->gen() . 'pub_key.pem');
        $twoPlatformPublicKeyInstance = Rsa::from($platformPublicKeyFilePath, Rsa::KEY_TYPE_PUBLIC);

        // 「微信支付公钥」的「微信支付公钥ID」
        // 需要在 商户平台 -> 账户中心 -> API安全 查询
        $platformPublicKeyId = 'PUB_KEY_ID_0117024788722024122500218500000949';

        // 构造一个 APIv3 客户端实例
        $instance = Builder::factory([
            'mchid'      => $this->merchantId,
            'serial'     => $merchantCertificateSerial,
            'privateKey' => $merchantPrivateKeyInstance,
            'certs'      => [
                $platformPublicKeyId => $twoPlatformPublicKeyInstance,
            ],
        ]);

        $res = $instance->v3->fundApp->mchTransfer->transferBills->outBillNo->$out_bill_no->getAsync([
            // Query 参数
        ])->then(static function(\Psr\Http\Message\ResponseInterface $response) use($out_bill_no){
                $arr = json_decode((string) $response->getBody(), true);
                if($arr){
                    if($arr['state']=='SUCCESS'){
                        Db::table("store_member_bill")->where(['out_trade_no'=>$out_bill_no])->update(['state'=>$arr['state'],'status'=>'已收款']);
                    }else{
                        Db::table("store_member_bill")->where(['out_trade_no'=>$out_bill_no])->update(['state'=>$arr['state']]);
                    }
                    return $arr['state'];
                }else{
                    return '';
                }
            })->wait();
        return $this->api_result(200, '请求成功', $res);
    }



    public function callback(){
        $file = 'sites.log';
        file_put_contents($file, $_REQUEST, FILE_APPEND | LOCK_EX);
    }


    //# 获取应用根目录
    public function gen()
    {
        # 这里是判断命令行执行，还是浏览器执行
        if ('cli' == PHP_SAPI) {
            $scriptName = realpath($_SERVER['argv'][0]);
        } else {
            # 获取文件的绝对路径
            $scriptName = $_SERVER['SCRIPT_FILENAME'];
        }
        # dirname是获取目录，reapath返回绝对路径
        $path = realpath(dirname($scriptName));
        # 检测是不是文件
        if (!is_file($path . DIRECTORY_SEPARATOR . 'think')) {
            $path = dirname($path);
        }
        return $path . DIRECTORY_SEPARATOR;
    }



    public function ceshi(){
        $merchantPrivateKeyFilePath = file_get_contents($this->gen() . 'apiclient_key.pem');

        $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);

        $merchantCertificateSerial = '79056050BF7311F2E85AE07C2EDD1E47DBB36914';


        // 从本地文件中加载「微信支付公钥」，用来验证微信支付应答的签名
        $platformPublicKeyFilePath    = file_get_contents($this->gen() . 'pub_key.pem');
        $twoPlatformPublicKeyInstance = Rsa::from($platformPublicKeyFilePath, Rsa::KEY_TYPE_PUBLIC);

        // 「微信支付公钥」的「微信支付公钥ID」
        // 需要在 商户平台 -> 账户中心 -> API安全 查询
        $platformPublicKeyId = 'PUB_KEY_ID_0117024788722024122500218500000949';

        // 构造一个 APIv3 客户端实例
        $instance = Builder::factory([
            'mchid'      => $this->merchantId,
            'serial'     => $merchantCertificateSerial,
            'privateKey' => $merchantPrivateKeyInstance,
            'certs'      => [
                $platformPublicKeyId => $twoPlatformPublicKeyInstance,
            ],
        ]);

        $resp = $instance->v3->fundApp->mchTransfer->transferBills->postAsync(
            [ 'json' =>
                [ 'appid' => 'wxf636efh567hg4356',
                    'out_bill_no' => 'plfk2020042013',
                    'openid' => 'o-MYE42l80oelYMDE34nYD456Xoy',
                    'user_name' => '757b340b45ebef5467rter35gf464344v3542sdf4t6re4tb4f54ty45t4yyry45',
                    'transfer_amount' => 400000,
                    'transfer_remark' => '2020年4月报销',
                    'notify_url' => '
https://www.weixin.qq.com/wxpay/pay.php',
                    'user_recv_perception' => '现金奖励',
                    'transfer_scene_id' => '1000',
                    'transfer_scene_report_infos' =>
                        [['info_type' => '活动名称',
                            'info_content' => '注册会员有礼',
                        ],],
                ],
                'headers' =>
                    [ 'Wechatpay-Serial' => 'PUB_KEY_ID_0117024788722024122500218500000949',
                    ],
            ])
            ->then(static function(\Psr\Http\Message\ResponseInterface $response) {
                print_r(json_decode((string) $response->getBody(), true));
            })
            ->wait();

        dump($resp);
    }

}